<template>
  <div class="container" style="margin-top: 50px;padding: 10px">
    <div class="row">
  <div class="col-md-4 messageContainer">
    <div class="left">
      <div  style="height: 70px; display: flex;justify-content: space-between;padding-right: 5px">
        <div style="line-height: 70px;color: #13ce66;cursor:pointer" @click="backHome"><i class="icon-fanhui  iconfont"></i>返回主页面</div>
        <h3 style="line-height: 70px"> 用户 ：{{username}} </h3>
      </div>
      <div style="border-bottom: 1px solid white">
      <div @click="jumpInto(item)" v-for="item in haveReceive">
        <div
          class="item"
          style="height: 80px"
          >
          <el-avatar
            :src="item.img"
          ></el-avatar>
          <div class="messageDetail" style="display: flex;flex-direction: column;padding: 10px">
            <div >我是&nbsp{{item.username}}<div></div>
            <div>最新信息：{{item.content}}</div>
          </div>
        </div>
        </div>
      </div>
      </div>
      <div v-if="haveReceive.length===0" style="font-size: 20px;text-align: center;line-height:550px ">暂无联系信息</div>
    </div>
  </div>
    <div class="col-md-8 roomContainer ">
      <div class="roomContainer">
        <div class="headerContainer">
          <h3>正在和 {{tousername}} 聊天 </h3>
        </div>
        <div class="mainContainer" style="padding:10px" id="container">
            <div  v-for="item in message">
<!--              绯色下午茶发给我的  所以tousername 是我自己-->
              <div  class="leftContainer"  v-if="item.tousername === username">
              <el-avatar
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                style="height: 40px"
              ></el-avatar>
              <div class="box">{{item.content}}</div>
            </div>

              <div  class="rightContainer"  v-else >
                            <el-avatar
                              :src="currentUserImg"
                              style="height: 40px;float: right;"
                            ></el-avatar>
                            <div class="box2" >{{item.content}}</div>
              </div>
            </div>
<!--              我发给绯色下午茶的  tousername是 绯色下午茶-->
<!--            <el-avatar-->
<!--              :src="currentUserImg"-->
<!--              style="height: 40px;float: right;"-->
<!--            ></el-avatar>-->
<!--            <div class="box2" >{{item.content}}</div>-->
<!--              </div>-->

        </div>
        <div class="inputContainer" style="border-top:1px solid gainsboro;margin-top: 2px">
          <textarea
            @keydown.enter="sendInfo"
            style="resize:none;width: 100%"
            placeholder="发点什么吧..."
            v-model="textInfo"
            rows="4"
            class="input"
          ></textarea>
          <div class="send">
            <el-button type="success" @click="sendInfo" >发送</el-button>
          </div>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>
<script>
import Room from '../Room/index'
import {baseUrl, rightUrl, wsUrl} from '../../utils/Address'
import Moment from 'moment'
export default {
  mounted () {
    this.ws = new WebSocket(wsUrl + `/${this.username}`)
    this.ws.onopen = this.onOpen
    this.ws.onError = this.onError
    this.ws.onmessage = this.onMessage
    this.ws.onclose = this.onClose
    this.getAllMesaage()
    this.getUserImg(this.userid)
  },
  components: {
    Room
  },
  data () {
    return {
      haveSend:[],
      message:[],
      tousername: '',
      ws: Object,
      textInfo:'',
      username: window.localStorage.getItem('username') || '',
      haveReceive: [],
      userid:window.localStorage.getItem('userId')||'',
      currentUserImg:'',
    }
  },
  methods: {
    update(){
        let div=document.getElementById('container')
        div.scrollTop=div.scrollHeight
    },
    backHome(){
      this.$router.replace('/')
    },
    jumpInto (item) {
      console.log(111)
      console.log(this.message)
      console.log(item)
      this.tousername=item.username
      this.getToUserNameMsg(this.tousername)
    },
       getToUserNameMsg (name) {
        let Infos=[]
         this.axios(`${baseUrl}/msg/getcurr/${name}`).then(
         res=>{
           let Arr=res.data.data
           console.log(Arr)
           this.update()
           let from = Arr.fromMe
           let other = Arr.toMe
           // from.concat(other)
           Infos = from.concat(other)
           Infos.forEach(item=>{
               item.sendtime=Moment(item.sendtime).valueOf()
             }
           )
           Infos.sort(function (a,b) {
             return  a['sendtime'] - b['sendtime']
           })
           console.log(Infos)
           this.message=Infos
           this.update()
         }
       ).catch(err=>{
         this.$message.error(`对不起，获取与${this.tousername}聊天记录失败，刷新重试`)
       })

      },
    getAllMesaage(){
        this.axios.get(`${baseUrl}/msg/getAllMyMsg`).then(res=>{
          const {data} =res.data
          var img=rightUrl
          var info={}
          data.forEach(item=>{
            console.log(item)
            if(item.userName===this.username){
               if(item.messages.length===1){
                 let id= item.messages[0].senduserid
                   info.content=item.messages[0].content
                   this.axios.get(`${baseUrl}/user/userinfo/${id}`).then(
                    res=>{
                       img=res.data.data.uimage
                    }
                  )
                 info.img=img
                 info.username=item.messages[0].username
                 console.log(info)
               }else {
                  let length=item.messages.length
                 let id =item.messages[length-1].senduserid
                 info.content=item.messages[length-1].content
                 this.axios.get(`${baseUrl}/user/userinfo/${id}`).then(
                   res=>{
                     img=res.data.data.uimage
                   })
                 info.username=item.messages[0].username
                 info.img=img
                 console.log(info)
               }
            }
          })
          this.haveReceive.push(info)
        }).catch(err=>{
          this.$message.error("对不起，获取用户列表失败啦，尝试刷新")
          }
        )
    },
     getUserImg(userId){
     this.axios.get(`${baseUrl}/user/userinfo/${userId}`).then(
        res=>{
          this.currentUserImg=res.data.data.uimage
          console.log(this.currentUserImg)
        }
      )

    },
    onOpen () {
      console.log('open')
    },
    onError () {
      this.$message.error("对不起，websocket链接建立失败，刷新重试")
      console.log('error')
    },
    onMessage (event) {
      console.log(222)
      this.haveReceive=[]
      let res = JSON.parse(event.data)
      console.log(res)
      this.getAllMesaage()
      this.getToUserNameMsg(this.tousername)
      console.log(this.haveReceive)
      this.haveReceive.forEach(
          item=>{
            console.log(item)
            if(item.tousername===res.tousername)
               this.haveReceive[length]=item
            else
              this.haveReceive.push(item)
      }
    )
    },
    onClose () {
      console.log('close')
    },
    handlePushKeyword(event){
      console.log(111)
      if (event.keyCode === 13) {
        event.preventDefault(); // 阻止浏览器默认换行操作
        this.sendInfo(); // 发送文本
        return false;
      }
    },
    sendInfo(){
      if(this.tousername===''){
        this.textInfo=''
        this.$message.error("选择联系人！！！")
        return false
      }
      let date = Moment().format('YYYY-MM-D HH:mm:ss')
      let infos={
        content: this.textInfo,
        sendtime:date,
        tousername:this.tousername,
        username: this.username
      }
      this.update()
      this.message.push(infos)
      let info={'username':this.username,'tousername':this.tousername,'content':this.textInfo.trim(),'sendtime':date}
      this.ws.send(JSON.stringify(info))
      this.textInfo=''
      this.update()
    }
  }
}
</script>
<style scoped>
.el-input{
  width: 200px;
}
.messageContainer {
  height: 650px;
  background-color: rgba(236, 231, 231,.5);
}
.el-avatar{
  margin-top: 10px;

}
.item{
  display: flex;
}
.messageDetail{
  padding: 6px;
  flex-grow: 2;
  flex-direction: column;
}
.topContainer{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.messageDetail>div{
  height: 30px;
  line-height: 30px;
  font-size: 14px;
}
.roomContainer{
  background-color: rgb(245, 246, 247);
  height: 650px;
  border-left: 1px solid white;
}
.box {
  margin-top: -40px;
  margin-left: 60px;
  width: 100px;
  min-height: 50px;
  padding: 10px;
  color: white;
  background: rgb(31, 186, 252);
  position: relative;
  border-radius:10px;
  border:1px solid #1FBAFC;
}
.box:before{
  content:"";
  position: absolute;
  right: 100%;
  width: 0;
  height: 0;
  border-top: 12px solid transparent;
  border-right: 6px solid #1FBAFC;
  border-bottom: 9px solid transparent;
}
.box:after {
  content:"";
  position: absolute;
  right: 100%;
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-right: 10px solid #1FBAFC;
  border-bottom: 10px solid transparent;
}
.box2 {
  float: right;
  margin-right: 20px;
  width: 100px;
  padding: 10px;
  color: white;
  min-height: 50px;
  background: #1FBAFC;
  position: relative;
  border-radius:10px;
  border:1px solid #1FBAFC;
}
.box2:before{
  content:"";
  position: absolute;
  left: 100%;
  top: 16px;
  width: 0;
  height: 0;
  border-top: 12px solid transparent;
  border-left: 12px solid #1FBAFC;
  border-bottom: 12px solid transparent;
}
.box2:after {
  content:"";
  position: absolute;
  left: 100%;
  top: 18px;
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-left: 10px solid #1FBAFC;
  border-bottom: 10px solid transparent;
}
.headerContainer{
  height: 70px;
}
.inputContainer{
  height: 100px;
}
.headerContainer>h3{
  line-height: 70px;
}
.rightContainer{
  width: 100%;
  min-height: 100px;
}
.leftContainer{
  width: 100%;
  min-height: 100px;

}
.rightContainer,.leftContainer{
  font-size: 10px;
}
.mainContainer{
  background-color: white;
  height: calc( 550px - 170px);
  overflow: auto;
}
.send{
  margin-right: 5px;
  margin-bottom: 5px;
  float: right;
}


.input {
  border:0;
  padding:10px;
  font-size:1.3em;
  font-family:"Ubuntu Light","Ubuntu","Ubuntu Mono","Segoe Print","Segoe UI";
  color:#ccc;
  border:solid 1px #ccc;
  margin:0 0 1px;
  width:300px;
  -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
  -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
  box-shadow: inner 0 0 4px rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;

}
input:focus {
  outline: none !important;
  border-color: #719ECE;
  box-shadow: 0 0 10px #719ECE;
}
</style>
